const url = require('url');
const http = require('http');

process.on('message', (message) => {
  const {type, options} = message;
  if (type === 'send') {
    const urlObj = url.parse(options.url);
    const config = {
      hostname: urlObj.hostname
      , port: urlObj.port
      , path: urlObj.path
      , method: options.message
    };
    const client = http.request(config, res => {
      const chunks = [];
      res.on('data', chunk => {
        chunks.push(chunk);
      });
      res.on('end', chunk => {
        process.send({
          type: 'response'
          , data: JSON.parse(Buffer.concat(chunks).toString())
        });
        process.exit();
      });
    });
    client.end();
  }
});
